package stark.app.function.filetransfer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.file.transfer.FileReceiveScanQrActivity;
import com.stark.file.transfer.FileReceiveScanQrActivity1;
import com.stark.file.transfer.FileSendShowQrActivity;
import com.stark.file.transfer.FileSendShowQrActivity1;
import com.stark.file.transfer.core.FileInfo;
import com.stark.file.transfer.core.TfContactInfo;
import com.stark.file.transfer.core.Transferable;
import com.stark.file.transfer.core.TransferableSendManager;
import com.stark.fileserver.lib.StkFileServerConfig;
import com.stark.fileserver.lib.StkFileServerListener;
import com.stark.fileserver.lib.StkFileServerService;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.base.BaseWithFragmentActivity;
import stark.app.databinding.ActivityFileTransferBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.bean.ContactInfo;
import stark.common.basic.constant.FileType;
import stark.common.basic.utils.ContactUtil;
import stark.common.basic.utils.LocationUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * 文件传输demo界面
 */
public class FileTransferActivity extends BaseNoModelActivity<ActivityFileTransferBinding> implements View.OnClickListener {

    @Override
    protected int onCreate() {
        return R.layout.activity_file_transfer;
    }

    @Override
    protected void initView() {
        mDataBinding.btnTfVideoImg.setOnClickListener(this);
        mDataBinding.btnTfReceive.setOnClickListener(this);
        mDataBinding.btnTfContact.setOnClickListener(this);

        mDataBinding.btnTfVideoImg1.setOnClickListener(this);
        mDataBinding.btnTfReceive1.setOnClickListener(this);
        mDataBinding.btnTfContact1.setOnClickListener(this);
        mDataBinding.btnSendApk.setOnClickListener(this);

        mDataBinding.btnStartFileServer.setOnClickListener(v -> {
            StkPermissionHelper.permission(Manifest.permission.MANAGE_EXTERNAL_STORAGE)
                    .reqPermissionDesc("启动文件服务器需要文件管理权限")
                    .callback(new StkPermissionHelper.ACallback() {
                        @Override
                        public void onGranted() {
                            StkFileServerConfig serverConfig = null;
                            //如有需要，可自己配置文件服务器的相关根目录路径及端口，不配置将使用默认的
                            //serverConfig = new StkFileServerConfig();
                            //serverConfig.showAllFileInRoot = true; //为true，显示根目录下所有文件。为false，显示根目录下部分文件夹
                            StkFileServerService.start(FileTransferActivity.this, serverConfig, new StkFileServerListener() {
                                @Override
                                public void onFileServerStartSuccess(String ip, int port) {
                                    mDataBinding.tvStartFileServerRet.setVisibility(View.VISIBLE);
                                    mDataBinding.btnStopFileServer.setVisibility(View.VISIBLE);
                                    String text = "文件服务启动成功：您可在电脑或手机浏览器中输入(http://" + ip + ":" + port + "/)访问该手机文件系统,在浏览器访问过程中，请确保手机不要熄屏，否则无法正常访问。";
                                    mDataBinding.tvStartFileServerRet.setText(text);
                                }

                                @Override
                                public void onFileServerStartFailure(String failMsg) {
                                    mDataBinding.tvStartFileServerRet.setVisibility(View.VISIBLE);
                                    mDataBinding.tvStartFileServerRet.setText("文件服务启动失败，失败原因为：" + failMsg);
                                }

                                @Override
                                public void onFileServerStop() {
                                    mDataBinding.tvStartFileServerRet.setVisibility(View.GONE);
                                    mDataBinding.btnStopFileServer.setVisibility(View.GONE);
                                }
                            });
                        }
                    })
                    .request();
        });
        mDataBinding.btnStopFileServer.setOnClickListener(v -> {
            StkFileServerService.stop(FileTransferActivity.this);
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_tf_video_img) {
            clickSendVideoImg(false);
        } else if (id == R.id.btn_tf_receive) {
            clickReceive(false);
        } else if (id == R.id.btn_tf_contact) {
            clickSendContact(false);
        } else if (id == R.id.btn_tf_video_img1) {
            clickSendVideoImg(true);
        } else if (id == R.id.btn_tf_receive1) {
            clickReceive(true);
        } else if (id == R.id.btn_tf_contact1) {
            clickSendContact(true);
        } else if (id == R.id.btnSendApk) {
            clickSendApk();
        }
    }

    private void clickSendVideoImg(boolean isFangAn1) {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.ALL)
                .maxCount(20)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        List<Transferable> fileInfoList = convert(data);
                        TransferableSendManager.getInstance().setTransferables(fileInfoList);

                        if (isFangAn1) {
                            startActivity(new Intent(FileTransferActivity.this, FileSendShowQrActivity1.class));
                        } else
                            //需要先开启位置服务，才能成功创建热点
                            if (LocationUtil.isLocationEnabled()) {
                                startActivity(new Intent(FileTransferActivity.this, FileSendShowQrActivity.class));
                            } else {
                                ToastUtils.showShort(R.string.open_location_service_tip);
                            }

                    }
                });
    }

    private void clickReceive(boolean isFangAn1) {
        //注意：这里当项目中需要用到的时候才去申请，当项目中没有传输联系人的功能时不要去申请
        StkPermissionHelper.permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_CONTACTS)
                .reqPermissionDesc("接收文件需要使用相机权限，用于扫描传输文件生成的二维码，接收图片、视频等文件需要存储权限，接收通讯录要将通讯录写入手机，需要写联系人权限，是否申请相关权限？")
                //下面注释的代码，是可自定义内部权限说明框的文本、颜色等，还有其它方法，自行去查看
//                .title("自定义标题")
//                .leftBtnText("左边按钮文本")
//                .leftBtnTextColor(Color.parseColor("#FF0000"))
//                .rightBtnText("右边按钮文本")
//                .rightBtnTextColor(Color.parseColor("#000000"))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        if (isFangAn1) {
                            startActivity(new Intent(FileTransferActivity.this, FileReceiveScanQrActivity1.class));
                        } else {
                            if (LocationUtil.isLocationEnabled()) {
                                startActivity(new Intent(FileTransferActivity.this, FileReceiveScanQrActivity.class));
                            } else {
                                ToastUtils.showShort(R.string.open_location_service_tip);
                            }
                        }
                    }
                })
                .request();
    }

    private List<Transferable> convert(List<SelectMediaEntity> list) {
        if (list == null || list.size() == 0) return null;
        List<Transferable> fileInfoList = new ArrayList<>();
        for (SelectMediaEntity entity : list) {
            String fileName = entity.getMediaName();
            FileType fileType = FileType.VIDEO;
            switch (entity.getType()) {
                case VIDEO:
                    fileType = FileType.VIDEO;
                    break;
                case AUDIO:
                    fileType = FileType.AUDIO;
                    break;
                case IMAGE:
                    fileType = FileType.IMAGE;
                    break;
            }
            FileInfo fileInfo = new FileInfo(fileName, entity.getUri(), fileType, entity.getSize());
            fileInfoList.add(fileInfo);
        }
        return fileInfoList;
    }

    private void clickSendContact(boolean isFangAn1) {
        PermissionUtils.permission(Manifest.permission.READ_CONTACTS)
                .callback(new PermissionUtils.SingleCallback() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (isAllGranted) {
                            sendContact(isFangAn1);
                        } else {
                            ToastUtils.showShort(com.stark.common.res.R.string.permission_no_granted);
                        }
                    }
                })
                .request();
    }

    private void clickSendApk() {
        BaseWithFragmentActivity.start(this, "发送APK", SendApkFragment.class);
    }

    private void sendContact(boolean isFangAn1) {
        showDialog("获取联系人中...");
        RxUtil.create(new RxUtil.Callback<List<ContactInfo>>() {
            @SuppressLint("MissingPermission")
            @Override
            public void doBackground(ObservableEmitter<List<ContactInfo>> emitter) {
                List<ContactInfo> contactInfoList = ContactUtil.getAllContact();
                //为了不把太多联系人发送到对方手机，所以这里只保留发送1条
                if (contactInfoList != null && contactInfoList.size() > 1) {
                    contactInfoList = contactInfoList.subList(0, 1);
                }
                emitter.onNext(contactInfoList);
            }

            @Override
            public void accept(List<ContactInfo> contactInfoList) {
                dismissDialog();

                List<Transferable> transferableList = new ArrayList<>();
                TfContactInfo tfContactInfo = new TfContactInfo(contactInfoList);
                transferableList.add(tfContactInfo);
                TransferableSendManager.getInstance().setTransferables(transferableList);
                if (isFangAn1) {
                    startActivity(new Intent(FileTransferActivity.this, FileSendShowQrActivity1.class));
                } else {
                    //需要先开启位置服务，才能成功创建热点
                    if (LocationUtil.isLocationEnabled()) {
                        startActivity(new Intent(FileTransferActivity.this, FileSendShowQrActivity.class));
                    } else {
                        ToastUtils.showShort(R.string.open_location_service_tip);
                    }
                }
            }
        });
    }

}